# 导入:
# import mysql.connector.errorcode
import sqlalchemy
from sqlalchemy import Column, String, Integer, Boolean
from utils.sql.db import session, Base
from utils.sql.app.user import User
import time
from utils.sql.public.location import phone_location


# 定义User对象:
class Feedback(Base):
    # 表的名字:
    __tablename__ = 'feedback'

    # 表的结构:
    id = Column(Integer(), primary_key=True, default=None)
    user_id = Column(String(20), default='')
    feed_back = Column(String(255), default='')
    dispose_state = Column(Boolean)
    create_time = Column(String(20), default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


def feedbacks(data, user_id):
    # print(data.phone_num)
    # return
    try:
        # 创建新Feedback对象:
        new_Feedback = Feedback(
            user_id=user_id,
            feed_back=data.content,
            create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        )
        if data.phone_num:
            location = ''
            location = phone_location(data.phone_num)
            user = session.query(User).filter(User.user_id == user_id).one()
            user.phone_num = data.phone_num
            user.native_place = location

        # 添加到session:
        session.add(new_Feedback)
        # 提交即保存到数据库:
        session.commit()
        return {
            "code": 200,
            "data": "",
            "message": "提交成功"
        }
    except sqlalchemy.exc.IntegrityError as e:
        return {
            "code": 201,
            "data": e,
            "message": "提交失败"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


